<?php

namespace app\api\model;

use think\Model;
use traits\model\SoftDelete;

class Users extends Model
{
    use SoftDelete;
    protected $autoWriteTimestamp = 'int';
    protected $deleteTime = 'deletetime';
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $hidden = ['deletetime', 'createtime', 'updatetime'];

    public function getOnTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }

    public function getIsVipAttr($value)
    {
        return $value === 'yes' ? 1 : 0;
    }

    public function getIsFreezeAttr($value)
    {
        return $value === 'yes' ? 1 : 0;
    }

    public static function getMoneyValue($user_id)
    {
        return self::where('id', $user_id)->value('money');
    }

    public function userVip()
    {
        return $this->hasOne(UserVip::class, 'name', 'vip');
    }

    public function userCoupons()
    {
        return $this->hasMany(UserCoupons::class, 'user_id', 'id')->where('status', 1);
    }

    /**
     * 会员折扣
     */
    public static function getVipDiscount($user_id, $pay = false)
    {
        $vip = self::where('id', $user_id)->value('vip');
        $discount =  UserVip::getDiscountByName($vip);
        //最优折扣
        $min_discount = UserVip::getLastDiscount();
        return ($discount ?: ($pay ? 100 :  $min_discount)) / 100;
    }
}
